

#include "Common.h"
#include "String.h"
#include "SharedPtr.h"
#include "ResourceManager.h"
#include "Database/DatabaseEnv.h"
#include "StringConverter.h"
#include "NGLog.h"
#include "MersenneTwister.h"
#include "ScriptMgr.h"
#include "Threading/Mutex.h"
#include "Game.h"
#include "Util.h"
#include "WorldPacket.h"
#include "Character.h"
#include "CharManager.h"
#include "WSSocket.h"
#include "Mails.h"
#include "Regions.h"
#include "RegionManager.h"
#include "ChannelManager.h"
#include "Message.h"
#include "PGWorldAIInterface.h"
#include "PGAIScript.h"
#include "PGPubStruct.h"
#include "PGRuleManager.h"
#include "Tools.h"
#include "VipCardManager.h"
#include "NoticeManager.h"
#include "CenterBankManager.h"
#include "ResourceEventEnum.h"
#include "GameDefine.h"
#include ENUM_PATH
#include LOGIC_MGR_PATH
#include XMLDATA_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include LOG_MGR_PATH




namespace AIScript
{
	//-----------------------------------------------------------------------
	PGCreatureInterface::PGCreatureInterface(Resource * pUnit):AICreatureBaseInterface(pUnit)
	{
		m_AIType = AITYPE_WCREATURE;
	}
	//-----------------------------------------------------------------------
	PGCreatureInterface::~PGCreatureInterface(void)
	{
	}
	//-----------------------------------------------------------------------
	void PGCreatureInterface::Load(void)
	{
		Character* chr = (Character*)m_Unit;
		chr->setStatus(CharacterStatusFree);
		// 合并物品
		CharPtr pSelf = ResourceProxy(m_Unit).getResourcePtr();
		sGLMgr.CombItemData(pSelf);
		
		AIInterface::Load();
	}
	//-----------------------------------------------------------------------
	void 	PGCreatureInterface::Update(const uint32 & p_time)
	{
		
		AIInterface::Update(p_time);
	}
	//-----------------------------------------------------------------------
	void PGCreatureInterface::ResetLossWinPerDay(const uint32 curTime, const bool bCancelLock)
	{
		if (!sTools.IsSameDate(m_Unit->getUInt32Field("marriage_time"), curTime))
		{
			int32 limit = (int32)sXmlDataMgr.GetConfXMLValue("LW_MAXCOIN");
			if (bCancelLock && limit > 0 && abs(m_Unit->getInt32Field("marriage")) >= limit)
			{
				CharPtr pChr = ResourceProxy(m_Unit).getResourcePtr();
				// 取消限制
				WorldPacket packet;
				if (sProtocolsMgr.CreateTellToDoPacket(&packet, en_RemindType_CancelLock))
					sPubLogic.SendProtocolsToChr(pChr, &packet);
			}
			m_Unit->setInt32Field("marriage", 0);
			m_Unit->setUInt32Field("marriage_time", curTime);
		}
	}
	//-----------------------------------------------------------------------
	const uint32 PGCreatureInterface::ComputeRealChip(const uint32 pos, const uint32 chip)
	{
		
	}
	//-----------------------------------------------------------------------
	bool PGCreatureInterface::AddChips(const uint32 pos, const uint32 chips, String fieldName)
	{
	
		return true;
	}
	
	const uint32 PGCreatureInterface::GetChip(const uint32 pos)
	{
			return 0;
	}
	//-----------------------------------------------------------------------
	const uint32 PGCreatureInterface::GetJoinCost()
	{
		return 0;
	}
	//-----------------------------------------------------------------------
	const uint32 PGCreatureInterface::GetFrozenCapital()
	{
		uint32 allFrozen = 0;
		return allFrozen;
	}
	//-----------------------------------------------------------------------
	uint32 PGCreatureInterface::GetGifts(const uint32 giftType)
	{
		uint32 result = en_GetGift_Faild;
		
		return result;
	}
	//-----------------------------------------------------------------------
	
	void PGCreatureInterface::ComputeNextOnlineGift()
	{
		CharPtr pChr = ResourceProxy(m_Unit).getResourcePtr();
		uint32 curTime = time(0);
		if (!sTools.IsSameDate(m_Unit->getUInt32Field("country_contribute"), curTime))
		{
			m_Unit->setUInt32Field("country_noble", 1);
		}
		uint32 num = m_Unit->getUInt32Field("country_noble");
		if (num <= sXmlDataMgr.GetMaxOnlineId())
		{
			m_Unit->setUInt32Field("country_contribute", curTime);
			// 下级在线奖励
			// uint32 interval = sXmlDataMgr.GetSecondsOfOnline(num);
			// uint32 nextCoins = sXmlDataMgr.GetBountyOfOnline(num);
			WorldPacket packet;
		}
	}

	bool PGCreatureInterface::AddNewTitle(const uint32 titleId)
	{
		Character* pChr = (Character*)m_Unit;
		String key_name = "TITLES";
		if(pChr->user_data.isPresented(key_name))
		{
			String titles;
			pChr->user_data.Get<String>(key_name, titles);
			titles = titles + StringConverter::toString(titleId) + " " + StringConverter::toString(uint32(time(0))) + ",";
			pChr->user_data.Set<String>(key_name, titles);
		}
		else
		{
			String title = StringConverter::toString(titleId) + " " + StringConverter::toString(uint32(time(0))) + ",";
			pChr->user_data.New<String>(key_name, title);
		}
		pChr->user_data.Save();
		return true;
	}
	//-----------------------------------------------------------------------
	void PGCreatureInterface::UpdateExps(ResourceEvent * event)
	{
		PGChannelInterface *pChnAiInfe;
		if (event && !event->source.isNull() && 
			NULL != (pChnAiInfe = TO_CHANNEL_INTERFACE(event->source.getResourcePtr()->getAIInterface())))
		{
			// 获取当前等级
			uint32 lv = m_Unit->getUInt32Field("lv");
			if (lv == sXmlDataMgr.GetMaxLevel())
				return;
			std::vector<TablePlayer> &vecPos = pChnAiInfe->GetPositionInfo();
			uint32 exps = 0;
			uint32 addExp = sXmlDataMgr.GetConfXMLValue("DOOR_EXP");
			if (m_Unit->getHandle() == event->idata)
			{
				if (event->idata4 == PGChannelInterface::en_ResultType_FullWin)
				{
					exps = 3 * addExp * 3;
				}
				else
				{
					for (size_t i = 1; i != vecPos.size(); ++i)
					{
						if (!vecPos[i].isWin) // 该门输，庄家赢
							exps += addExp;
					}
				}
			}
			else
			{
				for (size_t i = 1; i != vecPos.size(); ++i)
				{
					if (GetChip(i) && vecPos[i].isWin)
						exps += addExp;
				}
			}
			CharPtr pChr = ResourceProxy(m_Unit).getResourcePtr();
			// 检测是否有双
			sVipCardMgr.AddExps(pChr, exps);
			// 添加经验
			uint32 curExp = m_Unit->getUInt32Field("exps") + exps;
			UserPtr pUser = sUserMgr.getByHandle(m_Unit->getUInt32Field("userid"));
			if (!pUser.isNull())
			{
				char msg[256];
				char strExpAdd[] = "exp_add";
				sprintf(msg, sPubLogic.GetMsgData(strExpAdd, pUser).c_str(), event->source.getResourcePtr()->getUInt32Field("mapid"), exps);
				sPubLogic.SendSystemMessage(pChr, msg, sPubLogic.GetMsgType(strExpAdd, pUser));
			}
			// 获取升下级所需经验
			uint32 nextExp = sXmlDataMgr.GetExpsOfLevel(lv);
			if (curExp >= nextExp) // 升级了
			{
				curExp -= nextExp;
				m_Unit->setUInt32Field("lv", lv + 1);
				// 赠送财神卡
				sPubLogic.MammonCome(pChr, true);
				// 获得升级奖励
				uint32 levelUphr = sXmlDataMgr.GetLevelUpGiftOfLevel(lv);
				if (pChr->getUInt32Field("rank"))
					levelUphr += sXmlDataMgr.GetConfXMLValue("YD_LVUP");
				ItemPtr item = sPubLogic.addItemNum(pChr, ItemModel_Coins, levelUphr);
				if (!item.isNull())
				{
					WorldPacket packet;
					if (sProtocolsMgr.CreateTellToDoPacket(&packet, en_RemindType_LevelUp, lv + 1, levelUphr))
						sPubLogic.SendProtocolsToChr(pChr, &packet);
					// // 消息
					// char msg[256];
					// sprintf(msg, (sPubLogic.GetMsgData("level_up")+sPubLogic.GetMsgData("item_num")).c_str(), levelUphr);
					// sPubLogic.SendSystemMessage(pChr, msg, sPubLogic.GetMsgType("level_up"));
					// 记录日志
					sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_GiftBag, ItemModel_Coins, en_UNT_Add, levelUphr, en_GiftType_LevelUp);
				}
			}
			m_Unit->setUInt32Field("exps", curExp);
		}
	}
	//-----------------------------------------------------------------------
	void PGCreatureInterface::Compensate()
	{
		CharPtr pChr = sCharMgr.getByHandle(m_Unit->getHandle());
		UserPtr pUser = sUserMgr.getByHandle(m_Unit->getUInt32Field("userid"));
		if (pUser.isNull())
		{
			return;
		}
		if (pUser->getUInt32Field("ll_time") > 1374775200 && pUser->getUInt32Field("ll_time") < 1374822411)
		{
			// 补10W
			sPubLogic.addItemNum(pChr, ItemModel_Coins, 100000);
			// 消息
			char msg[256];
			char strCompen[] = "compensate";
			sprintf(msg, sPubLogic.GetMsgData(strCompen, pUser).c_str());
			sPubLogic.SendSystemMessage(pChr, msg, sPubLogic.GetMsgType(strCompen, pUser));
			// 记录日志
			sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_GiftBag, ItemModel_Coins, en_UNT_Add, 100000, en_GiftType_Compensate);
			GameMail *pNewMail = sChannelMgr.newDumyMail();
			if (NULL != pNewMail)
			{
				pNewMail->group_id = pChr->getGroup_id(); // 邮件组ID
				pNewMail->status = Mail::MailStatusRecv; // 邮件状态
				pNewMail->recv_serial = pUser->getUInt32Field("platform_id"); // 接收方用户ID
				char strCompensate[] = "compensate_title";
				pNewMail->title = ServerDatabase.EscapeString(sPubLogic.GetMsgData(strCompensate, pUser)); // 标题
				pNewMail->contenct = ServerDatabase.EscapeString(msg); // 内容
				pNewMail->data1 = pUser->getUInt32Field("gz_id"); // 游戏类型
				pNewMail->create_time = time(0); // 创建时间
				// 保存到数据库
				sChannelMgr.addMailDB(pNewMail);
			}
			sChannelMgr.freeDumyMail(pNewMail);
		}
	}
}
